#include "Buffer.h"

#include <errno.h>
#include <sys/uio.h>
#include <unistd.h>

/**
 * @brief 接收fd数据
 *
 * @param fd
 * @param saveErrno
 * @return ssize_t
 */
ssize_t Buffer::readFd(int fd, int *saveErrno)
{
    char extrabuf[65536] = {0};

    struct iovec vec[2];
    const size_t writeable = writableBytes();
    vec[0].iov_base = begin() + writerIndex_;
    vec[0].iov_len = writeable;
    vec[1].iov_base = extrabuf;
    vec[1].iov_len = sizeof(extrabuf);

    const int iovcnt = (writeable < sizeof(extrabuf) ? 2 : 1);
    const ssize_t n = ::readv(fd, vec, iovcnt); // 多空间读取数据
    if (n < 0)                                  // 读取数据失败
    {
        *saveErrno = errno;
    }
    else if (n <= writeable) // 读取数据小于buffer可写数据
    {
        writerIndex_ += n;
    }
    else // extrabuf也写入了数据
    {
        writerIndex_ = buffer_.size();
        append(extrabuf, n - writeable); // 追加
    }
    return n;
}
/**
 * @brief 向fd发送数据
 *
 * @param fd
 * @param saveErrno
 * @return ssize_t
 */
ssize_t Buffer::writeFd(int fd, int *saveErrno)
{
    ssize_t n = ::write(fd, peek(), readableBytes());
    if (n < 0)
    {
        *saveErrno = errno;
    }
    return n;
}